<?php
if (!defined('IN_IPB')) exit("<h1>Incorrect access</h1> You may not access this file without the acp.");

class userstore extends template_plugin
{
	var $ipsclass;
	
	var $name = "User Store";
	var $multiple = 0;
	
	var $settings = array();
	
	var $order = array(
							'item' => 'item',
							'icon' => '',
							'name' => '',
							'category' => '',
							'price' => 'store_price',
							'listed' => 'listed',
							'expired' => 'expired',
						);
	var $order_by = array(
							'ASC' => 1,
							'DESC' => -1,
						);
	var $order_default = array(
									'item' => 'ASC',
									'icon' => 'ASC',
									'name' => 'ASC',
									'category' => 'ASC',
									'price' => 'ASC',
									'listed' => 'DESC',
									'expired' => 'DESC',
								);
	
	function acp_menu()
	{
		return array(
					  1 => array('Selling Items','code=plugin&do=run&link='.$this->plugin['link'].'&action=list'),
					  2 => array('Sold Items','code=plugin&do=run&link='.$this->plugin['link'].'&action=sold'),
					);
	}
	
	function acp()
	{
		$redirect = array(
							'list' => 'list_items',
							'sold' => 'list_completed',
						);
		
		if(!isset($redirect[$this->ipsclass->input['action']]))
		{
			$this->ipsclass->input['action'] = 'list';
		}
		
		$function = 'acp_'.$redirect[$this->ipsclass->input['action']];
		$this->$function();
	}
	
	function acp_list_items()
	{
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		$LIMIT = 50;
		
		$this->ipsclass->admin->page_title  = "Welcome to selling item list";
		$this->ipsclass->admin->page_detail = "Welcome to selling item list.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code, 'List Selling Items' );
		
		$total = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_user_store_item'));
		$page = $this->ipsclass->adskin->build_pagelinks(	array(	'TOTAL_POSS'   => $total['total'],
																	'PER_PAGE'     => $LIMIT,
																	'USE_ST'       => 'st',
																	'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																	'L_SINGLE'     => "Single Page",
																	'BASE_URL'     => $this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;action=list"
															)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->html .= "<br />";
		
		$this->ipsclass->adskin->td_header[] = array( "Icon"             , "1%"  );
		$this->ipsclass->adskin->td_header[] = array( "Name/Description" , "50%" );
		$this->ipsclass->adskin->td_header[] = array( "IP Address"       , ""    );
		$this->ipsclass->adskin->td_header[] = array( "Seller"           , ""    );
		$this->ipsclass->adskin->td_header[] = array( "Store Price"      , ""    );
		$this->ipsclass->adskin->td_header[] = array( "Listed On"        , ""    );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Selling Items");
		
		$this->ipsclass->DB->build_query(array(
												'select' => 'i.*',
												'from' => array('market_user_store_item'=>'i'),
												'add_join' => array(
																		array(
																				'select' => 'm.members_display_name as seller_name,m.mgroup as seller_group',
																				'from' => array('members'=>'m'),
																				'where' => "m.id=i.member_id",
																				'type' => 'left',
																			),
																	),
												'order' => 'i.listed DESC',
												'limit' => array($this->ipsclass->input['st'],$LIMIT),
										)	);
		$q = $this->ipsclass->DB->exec_query();
		while($item = $this->ipsclass->DB->fetch_row($q))
		{
			if(!is_array($this->ipsclass->cache['market_items'][$item['item']]))
			{
				$this->ipsclass->DB->do_delete('market_user_store_item',"i_id=".$item['i_id']);
				continue;
			}
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array(  
																				  "<img src='".$this->ipsclass->market_class->image_url_path."/icons/".$this->ipsclass->cache['market_items'][$item['item']]['icon']."' border='0' alt='Item Icon' />",
																				  "<b>".$this->ipsclass->cache['market_items'][$item['item']]['item_name']."</b><br />".$this->ipsclass->parser->pre_display_parse($this->ipsclass->parser->pre_db_parse($this->ipsclass->market_class->items_loaded[$item['item']]->parse_single_description($item))),
																				  $item['ip_address'],
																				  $this->ipsclass->market_admin->format_name($item['member_id'], $item['seller_name'],$item['seller_group']),
																				  $this->ipsclass->numbers->format_currency($item['store_price']),
																				  $this->ipsclass->get_date($item['listed'],'LONG'),
																		 )      );
		}
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No user store items selling",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->admin->output();
	}
	
	function acp_list_completed()
	{
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		$LIMIT = 50;
		
		$this->ipsclass->admin->page_title  = "Welcome to selling item list";
		$this->ipsclass->admin->page_detail = "Welcome to selling item list.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code, 'List Sold Items' );
		
		$total = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_user_store_logs'));
		$page = $this->ipsclass->adskin->build_pagelinks(	array(	'TOTAL_POSS'   => $total['total'],
																	'PER_PAGE'     => $LIMIT,
																	'USE_ST'       => 'st',
																	'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																	'L_SINGLE'     => "Single Page",
																	'BASE_URL'     => $this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;action=list"
															)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->html .= "<br />";
		
		$this->ipsclass->adskin->td_header[] = array( "Icon"             , "1%"  );
		$this->ipsclass->adskin->td_header[] = array( "Name/Description" , "50%" );
		$this->ipsclass->adskin->td_header[] = array( "Seller"           , ""    );
		$this->ipsclass->adskin->td_header[] = array( "Buyer"            , ""    );
		$this->ipsclass->adskin->td_header[] = array( "Buyer's IP"       , ""    );
		$this->ipsclass->adskin->td_header[] = array( "Price"            , ""    );
		$this->ipsclass->adskin->td_header[] = array( "Bought On"        , ""    );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Sold Items");
		
		$this->ipsclass->DB->build_query(array(
												'select' => 'i.*',
												'from' => array('market_user_store_logs'=>'i'),
												'add_join' => array(
																		array(
																				'select' => 's.members_display_name as seller_name,s.mgroup as seller_group',
																				'from' => array('members'=>'s'),
																				'where' => "s.id=i.seller_id",
																				'type' => 'left',
																			),
																		array(
																				'select' => 'b.members_display_name as buyer_name,b.mgroup as buyer_group',
																				'from' => array('members'=>'b'),
																				'where' => "b.id=i.buyer_id",
																				'type' => 'left',
																			),
																	),
												'order' => 'time_bought DESC',
												'limit' => array($this->ipsclass->input['st'],$LIMIT),
										)	);
		$q = $this->ipsclass->DB->exec_query();
		while($item = $this->ipsclass->DB->fetch_row($q))
		{
			if(!is_array($this->ipsclass->cache['market_items'][$item['item']]))
			{
				continue;
			}
			
			$item['price_bought'] = $item['price'];
			$item['resell_price'] = 0;
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array(  
																				  "<img src='".$this->ipsclass->market_class->image_url_path."/icons/".$this->ipsclass->cache['market_items'][$item['item']]['icon']."' border='0' alt='Item Icon' />",
																				  "<b>".$this->ipsclass->cache['market_items'][$item['item']]['item_name']."</b><br />".$this->ipsclass->parser->pre_display_parse($this->ipsclass->parser->pre_db_parse($this->ipsclass->market_class->items_loaded[$item['item']]->parse_single_description($item))),
																				  $this->ipsclass->market_class->format_name($item['seller_id'],$item['seller_name'],$item['seller_group']),
																				  $this->ipsclass->market_class->format_name($item['buyer_id'],$item['buyer_name'],$item['buyer_group']),
																				  $item['buyer_ip'],
																				  $this->ipsclass->numbers->format_currency($item['price']),
																				  $this->ipsclass->get_date($item['time_bought'],'LONG'),
																		 )      );
		}
		if($this->ipsclass->DB->get_num_rows() == 0)
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No user store items bought",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->admin->output();
	}
	
	function acp_install()
	{
		$this->ipsclass->DB->load_cache_file(ROOT_PATH.'sources/market/sql/'.$this->ipsclass->vars['sql_driver'].'_plugin_queries.php','sql_plugin_queries');
		
		$this->ipsclass->DB->sql_add_field("members","market_has_user_store"   , "tinyint(1) NOT NULL","'0'");
		$this->ipsclass->DB->sql_add_field("members","market_user_store_name"  ,"varchar(255) NOT NULL","''");
		$this->ipsclass->DB->sql_add_field("members","market_user_store_opened","int(10) NOT NULL","'0'");
		
		$this->ipsclass->DB->build_query_from_cache('table_user_store_item',array(),'sql_plugin_queries');
		$this->ipsclass->DB->exec_query();
		$this->ipsclass->DB->build_query_from_cache('table_user_store_logs',array(),'sql_plugin_queries');
		$this->ipsclass->DB->exec_query();
	}
	
	function acp_uninstall()
	{
		if($this->ipsclass->DB->field_exists("market_has_user_store"   , "members")) $this->ipsclass->DB->sql_drop_field('members','market_has_user_store'   );
		if($this->ipsclass->DB->field_exists("market_user_store_name"  , "members")) $this->ipsclass->DB->sql_drop_field('members','market_user_store_name'  );
		if($this->ipsclass->DB->field_exists("market_user_store_opened", "members")) $this->ipsclass->DB->sql_drop_field('members','market_user_store_opened');
		
		$this->ipsclass->DB->sql_drop_table( 'market_user_store_item' );
		$this->ipsclass->DB->sql_drop_table( 'market_user_store_logs' );
	}
	
	function run()
	{
		$this->ipsclass->load_template('skin_market_plugin');
		$this->ipsclass->load_language('lang_market_plugin');
		
		$this->ipsclass->market_class->title[] = array($this->plugin['name'],'market_'.$this->plugin['link']);
		if(in_array($this->ipsclass->member['mgroup'],$this->plugin['use_permission']))
		{
			if($this->ipsclass->member['market_has_user_store'])
			{
				$this->ipsclass->market_class->menu[] = array(
																"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->ipsclass->lang['ustore_list_stores']."</a></b>",
																"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=manage'>".$this->ipsclass->lang['ustore_manage_store']."</a></b>",
																"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=sold'>".$this->ipsclass->lang['ustore_sold_logs']."</a></b>",
																"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=bought'>".$this->ipsclass->lang['ustore_bought_logs']."</a></b>",
															);
			}
			else
			{
				$this->ipsclass->market_class->menu[] = array(
																"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->ipsclass->lang['ustore_list_stores']."</a></b>",
																"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=manage'>".$this->ipsclass->lang['ustore_create_a_store']."</a></b>",
																"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=bought'>".$this->ipsclass->lang['ustore_bought_logs']."</a></b>",
															);
			}
			
			$do_redirect = array(
									'list' => 'list_stores',
									'store' => 'list_items',
									'manage' => 'manage_store',
									'create' => 'create_store',
									'edit' => 'edit_store',
									'close' => 'close_store',
									'add' => 'add_items',
									'process' => 'process_items',
									'buy' => 'buy_items',
									'bought' => 'bought_items',
									'sold' => 'sold_items',
								  );
			
			if(!isset($do_redirect[$this->ipsclass->input['do']]))
			{
				$this->ipsclass->input['do'] = 'list';
			}
		}
		else
		{
			$this->ipsclass->market_class->menu[] = array(
															"<b><a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->ipsclass->lang['ustore_list_stores']."</a></b>",
														);
			
			$do_redirect = array(
									'list' => 'list_stores',
									'store' => 'list_items',
								  );
			
			if(!isset($do_redirect[$this->ipsclass->input['do']]))
			{
				$this->ipsclass->input['do'] = 'list';
			}
		}
		
		$func = 'run_'.$do_redirect[$this->ipsclass->input['do']];
		$this->$func();
	}
	
	function run_list_stores()
	{
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		$LIMIT = 50;
		
		$this->ipsclass->subtitle = $this->ipsclass->lang['ustore_list_stores'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->ipsclass->lang['ustore_list_stores']."</a>");
		
		$order_default = array(
								'name'   => array('m.market_user_store_name','ASC'),
								'member' => array('m.members_l_display_name','ASC'),
								'open'   => array('m.market_user_store_opened','DESC'),
								'noitem' => array('num_items','DESC'),
							);
		
		if(!isset($order_default[$this->ipsclass->input['order']]))
		{
			$this->ipsclass->input['order'] = 'noitem';
		}
		if(!isset($this->order_by[$this->ipsclass->input['by']]))
		{
			$this->ipsclass->input['by'] = $order_default[$this->ipsclass->input['order']][1];
		}
		
		if($this->ipsclass->input['by'] == $order_default[$this->ipsclass->input['order']][1])
		{
			if($order_default[$this->ipsclass->input['order']][1] == 'ASC')
			{
				$order_default[$this->ipsclass->input['order']][1] = 'DESC';
			}
			else
			{
				$order_default[$this->ipsclass->input['order']][1] = 'ASC';
			}
		}
		
		$order = $order_default[$this->ipsclass->input['order']][0]." ".$this->ipsclass->input['by'];
		
		$rows = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'members','where'=>"market_has_user_store=1"));
		$page_links = $this->ipsclass->build_pagelinks(	array(	'TOTAL_POSS'   => $rows['total'],
																'PER_PAGE'     => $LIMIT,
																'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																'L_SINGLE'     => $this->ipsclass->compiled_templates['skin_global']->pagination_compile($this->ipsclass->compiled_templates['skin_global']->pagination_make_jump(),"","",$this->ipsclass->compiled_templates['skin_global']->pagination_current_page(1),"","",1,$LIMIT,$this->ipsclass->market_class->base_url."plugin={$this->ipsclass->input['plugin']}&amp;do=list&amp;order=".$this->ipsclass->input['order']."&amp;by=".$this->ipsclass->input['by'],0,'st'),
																'BASE_URL'     => $this->ipsclass->market_class->base_url."plugin={$this->ipsclass->input['plugin']}&amp;do=list&amp;order=".$this->ipsclass->input['order']."&amp;by=".$this->ipsclass->input['by'],
																'USE_ST'       => 'st'
														)	);
		
		$stores = array();
		$this->ipsclass->DB->build_query(array(
												'select' => 'm.id,m.members_display_name,m.mgroup,m.market_user_store_name,m.market_user_store_opened',
												'from' => array('members'=>'m'),
												'add_join' => array(
																		array(
																				'select' => 'COUNT(i.i_id) as num_items',
																				'from' => array('market_user_store_item'=>'i'),
																				'where' => 'i.member_id=m.id',
																				'type' => 'left',
																			),
																	),
												'where' => "market_has_user_store=1",
												'group' => 'm.id',
												'order' => $order,
												'limit' => array($this->ipsclass->input['st'],$LIMIT)
										)	);
		$this->ipsclass->DB->exec_query();
		while($store = $this->ipsclass->DB->fetch_row())
		{
			$store['members_display_name'] = $this->ipsclass->market_class->format_name($store['id'],$store['members_display_name'],$store['mgroup']);
			$store['market_user_store_opened'] = $this->ipsclass->get_date($store['market_user_store_opened'],'LONG');
			$store['num_items'] = $this->ipsclass->do_number_format($store['num_items'],'LONG');
			$stores[] = $store;
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->ustore_list_stores($stores,$order_default,$page_links);
	}
	
	function run_create_store()
	{
		$this->ipsclass->DB->do_update('members',array(
														'market_has_user_store' => 1,
														'market_user_store_name' => $this->ipsclass->parser->bad_words($this->ipsclass->input['store_name']),
														'market_user_store_opened' => time(),
				),"id=".$this->ipsclass->member['id']);
		
		$this->ipsclass->market_class->redirect('ustore_store_created',"plugin=".$this->ipsclass->input['plugin']."&do=manage");
	}
	
	function run_manage_store()
	{
		if(!$this->ipsclass->member['market_has_user_store'])
		{
			$this->ipsclass->subtitle = $this->ipsclass->lang['ustore_create_a_store'];
			$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=manage'>".$this->ipsclass->lang['ustore_create_a_store']."</a>");
			
			$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->ustore_create_store();
			return;
		}
		
		$this->ipsclass->subtitle = $this->ipsclass->member['market_user_store_name'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=manage'>".$this->ipsclass->lang['ustore_manage_store']."</a>");
		
		$store_items = array();
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_user_store_item','where'=>"member_id=".$this->ipsclass->member['id']));
		$q = $this->ipsclass->DB->exec_query();
		while($item = $this->ipsclass->DB->fetch_row($q))
		{
			if(!is_array($this->ipsclass->cache['market_items'][$item['item']]))
			{
				$this->ipsclass->DB->do_delete('market_user_store_item',"i_id=".$item['i_id']);
				continue;
			}
			$item['description'] = $this->ipsclass->parser->pre_display_parse($this->ipsclass->parser->pre_db_parse($this->ipsclass->market_class->items_loaded[$item['item']]->parse_single_description($item)));
			$store_items[] = $item;
		}
		
		$inventory = array();
		foreach($this->ipsclass->market_class->inventory as $item_group)
		{
			foreach($item_group as $inv_item)
			{
				$inv_item['expired'] = $inv_item['expired'] == 0 ? $this->ipsclass->lang['never'] : $this->ipsclass->get_date($inv_item['expired'],'TINY');
				$inv_item['time_bought'] = $this->ipsclass->get_date($inv_item['time_bought'],'TINY');
				$inv_item['fprice_bought'] = $inv_item['price_bought'] <= 0 ? $this->ipsclass->lang['free'] : $this->ipsclass->numbers->format_currency($inv_item['price_bought']);
				$inv_item['fresell_price'] = $inv_item['resell_price'] <= 0 ? $this->ipsclass->lang['trash'] : $this->ipsclass->numbers->format_currency($inv_item['resell_price']);
				$inv_item['description'] = $this->ipsclass->parser->pre_display_parse($this->ipsclass->parser->pre_db_parse($this->ipsclass->market_class->items_loaded[$inv_item['item']]->parse_single_description($inv_item)));
				$inventory[] = $inv_item;
			}
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->ustore_manage_store($store_items, $inventory);
	}
	
	function run_edit_store()
	{
		$this->ipsclass->DB->do_update('members',array(
														'market_user_store_name' => $this->ipsclass->input['store_name'],
				),"id=".$this->ipsclass->member['id']);
		
		$this->ipsclass->market_class->redirect('ustore_store_info_saved',"plugin=".$this->ipsclass->input['plugin']."&do=manage");
	}
	
	function run_close_store()
	{
		if($this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'market_user_store_item','where'=>"member_id=".$this->ipsclass->member['id'],'limit'=>array(1))))
		{
			$this->ipsclass->Error(array('MSG'=>'ustore_empty_store_first'));
		}
		
		$this->ipsclass->DB->do_update('members',array(
														'market_has_user_store' => 0,
														'market_user_store_opened' => 0,
				),"id=".$this->ipsclass->member['id']);
		
		$this->ipsclass->market_class->redirect('ustore_store_closed',"plugin=".$this->ipsclass->input['plugin']);
	}
	
	function run_add_items()
	{
		if(is_array($this->ipsclass->input['item_id']))
		{
			foreach(array_keys($this->ipsclass->input['item_id']) as $item_id)
			{
				if(!isset($this->ipsclass->market_class->inventory_id[$item_id]))
				{
					unset($this->ipsclass->input['item_id'][$item_id]);
					continue;
				}
				
				$this->ipsclass->DB->do_insert('market_user_store_item',array(
																				'member_id' => $this->ipsclass->member['id'],
																				'item' => $this->ipsclass->market_class->inventory_id[$item_id]['item'],
																				'price_bought' => $this->ipsclass->market_class->inventory_id[$item_id]['price_bought'],
																				'resell_price' => $this->ipsclass->market_class->inventory_id[$item_id]['resell_price'],
																				'time_bought' => $this->ipsclass->market_class->inventory_id[$item_id]['time_bought'],
																				'settings' => $this->ipsclass->market_class->inventory_id[$item_id]['settings'],
																				'expired' => $this->ipsclass->market_class->inventory_id[$item_id]['expired'],
																				'ip_address' => $this->ipsclass->ip_address,
																				'listed' => time(),
																				'store_price' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['price'][$item_id],'int'),
											)								);
			}
			if(count($this->ipsclass->input['item_id']))
			{
				$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_inventory','where'=>"i_id IN (".implode(",",array_keys($this->ipsclass->input['item_id'])).")"));
			}
		}
		
		$this->ipsclass->market_class->redirect('ustore_items_added',"plugin=".$this->ipsclass->input['plugin']."&do=manage");
	}
	
	function run_process_items()
	{
		if(isset($this->ipsclass->input['prices']))
		{
			$this->run_process_new_prices();
		}
		elseif(isset($this->ipsclass->input['remove']))
		{
			$this->run_process_remove_items();
		}
		else
		{
			$this->ipsclass->Error(array('MSG'=>'incorrect_use'));
		}
	}
	
	function run_process_new_prices()
	{
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_user_store_item','where'=>"member_id=".$this->ipsclass->member['id']));
		$items = $this->ipsclass->DB->exec_query();
		while($item = $this->ipsclass->DB->fetch_row($items))
		{
			if(!isset($this->ipsclass->input['price'][$item['i_id']]))
			{
				continue;
			}
			
			$this->ipsclass->DB->do_update('market_user_store_item',array(
																			'store_price' => $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['price'][$item['i_id']],'int'),
											),"i_id=".$item['i_id']);
		}
		
		$this->ipsclass->market_class->redirect('ustore_item_prices_updated',"plugin=".$this->ipsclass->input['plugin']."&do=manage");
	}
	
	function run_process_remove_items()
	{
		$item_ids = array();
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_user_store_item','where'=>"member_id=".$this->ipsclass->member['id']));
		$items = $this->ipsclass->DB->exec_query();
		while($item = $this->ipsclass->DB->fetch_row($items))
		{
			if(!isset($this->ipsclass->input['item_id'][$item['i_id']]))
			{
				continue;
			}
			
			$item_ids[] = $item['i_id'];
			$this->ipsclass->DB->do_insert('market_inventory',array(
																		'member_id' => $this->ipsclass->member['id'],
																		'item' => $item['item'],
																		'price_bought' => $item['price_bought'],
																		'resell_price' => $item['resell_price'],
																		'time_bought' => $item['time_bought'],
																		'expired' => $item['expired'],
											)						);
			
		}
		if(count($item_ids))
		{
			$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_user_store_item','where'=>"i_id IN (".implode(",",array_keys($this->ipsclass->input['item_id'])).")"));
		}
		
		$this->ipsclass->market_class->redirect('ustore_item_removed',"plugin=".$this->ipsclass->input['plugin']."&do=manage");
	}
	
	function run_list_items()
	{
		$this->ipsclass->input['store'] = intval($this->ipsclass->input['store']);
		if($store = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'members','where'=>"id=".$this->ipsclass->input['store'])));
		else
		{
			$this->ipsclass->Error(array('MSG'=>'ustore_no_store'));
		}
		if(!$store['market_has_user_store'])
		{
			$this->ipsclass->Error(array('MSG'=>'ustore_no_store'));
		}
		
		$this->ipsclass->subtitle = $store['market_user_store_name'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=store&amp;store=".$this->ipsclass->input['store']."'>".$store['market_user_store_name']."</a>");
		
		if(!isset($this->order[$this->ipsclass->input['order']]))
		{
			$this->ipsclass->input['order'] = 'time';
		}
		if(!isset($this->order_by[$this->ipsclass->input['by']]))
		{
			$this->ipsclass->input['by'] = $this->order_default[$this->ipsclass->input['order']];
		}
		
		if($this->ipsclass->input['by'] == $this->order_default[$this->ipsclass->input['order']])
		{
			if($this->order_default[$this->ipsclass->input['order']] == 'ASC')
			{
				$this->order_default[$this->ipsclass->input['order']] = 'DESC';
			}
			else
			{
				$this->order_default[$this->ipsclass->input['order']] = 'ASC';
			}
		}
		
		$items = array();
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_user_store_item','where'=>"member_id=".$this->ipsclass->input['store']));
		$q = $this->ipsclass->DB->exec_query();
		while($item = $this->ipsclass->DB->fetch_row($q))
		{
			if(!is_array($this->ipsclass->cache['market_items'][$item['item']]))
			{
				$this->ipsclass->DB->do_delete('market_user_store_item',"i_id=".$item['i_id']);
				continue;
			}
			$items[] = $item;
		}
		
		usort($items,array(&$this,'order'));
		foreach($items as $i => $item)
		{
			$items[$i]['price'] = $this->ipsclass->numbers->format_currency($items[$i]['store_price']);
			$items[$i]['listed'] = $this->ipsclass->numbers->time_left($items[$i]['listed'],'TINY');
			$items[$i]['description'] = $this->ipsclass->parser->pre_display_parse($this->ipsclass->parser->pre_db_parse($this->ipsclass->market_class->items_loaded[$items[$i]['item']]->parse_single_description($items[$i])));
			$items[$i]['expired'] = $items[$i]['expired'] == 0 ? $this->ipsclass->lang['never'] : $this->ipsclass->get_date($items[$i]['expired'],'TINY');
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->ustore_list_items($store,$items,$this->order_default);
	}
	
	function run_buy_items()
	{
		$this->ipsclass->input['store'] = intval($this->ipsclass->input['store']);
		if($store = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'members','where'=>"id=".$this->ipsclass->input['store'])));
		else
		{
			$this->ipsclass->Error(array('MSG'=>'ustore_no_store'));
		}
		if(!$store['market_has_user_store'])
		{
			$this->ipsclass->Error(array('MSG'=>'ustore_no_store'));
		}
		
		$items = array();
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_user_store_item','where'=>"member_id=".$this->ipsclass->input['store']));
		$this->ipsclass->DB->exec_query();
		while($item = $this->ipsclass->DB->fetch_row())
		{
			$items[$item['i_id']] = $item;
		}
		
		$time = time();
		$total = 0;
		$delete = array();
		if(is_array($this->ipsclass->input['item']) and count($this->ipsclass->input['item']))
		{
			foreach($this->ipsclass->input['item'] as $i_id => $check)
			{
				if(!is_array($items[$i_id]) || $check != 1)
				{
					continue;
				}
				$delete[] = $i_id;
				$total = $this->ipsclass->numbers->add($total,$items[$i_id]['store_price']);
			}
		}
		
		if($this->ipsclass->numbers->compare($total,$this->ipsclass->member[$this->ipsclass->vars['market_members_field']]) > 0)
		{
			$this->ipsclass->Error(array('MSG'=>'ustore_not_enough_money'));
		}
		
		foreach($delete as $i_id)
		{
			$this->ipsclass->DB->do_insert('market_inventory',array(
																		'member_id' => $this->ipsclass->member['id'],
																		'item' => $items[$i_id]['item'],
																		'price_bought' => $items[$i_id]['store_price'],
																		'resell_price' => 0,
																		'time_bought' => $time,
																		'settings' => $items[$i_id]['settings'],
																		'expired' => $items[$i_id]['expired'],
											)						);
			
			$this->ipsclass->DB->do_insert('market_user_store_logs',array(
																			'seller_id' => $store['id'],
																			'buyer_id' => $this->ipsclass->member['id'],
																			'buyer_ip' => $this->ipsclass->ip_address,
																			'item' => $items[$i_id]['item'],
																			'time_bought' => $time,
																			'price' => $items[$i_id]['store_price'],
																			'settings' => $items[$i_id]['settings'],
												)						);
			
			$this->ipsclass->market_class->record_fee($items[$i_id]['store_price']);
		}
		if(count($delete))
		{
			$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_user_store_item','where'=>"i_id IN (".implode(",",$delete).")"));
		}
		
		$this->ipsclass->DB->do_update('members',array(
														$this->ipsclass->vars['market_members_field'] => $this->ipsclass->numbers->subtract($this->ipsclass->member[$this->ipsclass->vars['market_members_field']],$total),
				),"id=".$this->ipsclass->member['id']);
		$this->ipsclass->DB->do_update('members',array(
														$this->ipsclass->vars['market_members_field'] => $this->ipsclass->numbers->add($store[$this->ipsclass->vars['market_members_field']],$total),
								),"id=".$store['id']);
		
		$this->ipsclass->market_class->redirect('ustore_items_bought',"plugin=".$this->ipsclass->input['plugin']."&do=store&store=".$store['id']);
	}
	
	function run_bought_items()
	{
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		$LIMIT = 25;
		
		$this->ipsclass->subtitle = $this->ipsclass->lang['ustore_bought_logs'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=bought'>".$this->ipsclass->lang['ustore_bought_logs']."</a>");
		
		$rows = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_transfer_logs','where'=>"l_link='".$this->ipsclass->input['plugin']."' AND (l_from=".$this->ipsclass->member['id']." OR l_to=".$this->ipsclass->member['id'].")"));
		$page_links = $this->ipsclass->build_pagelinks(	array(	'TOTAL_POSS'   => $rows['total'],
																'PER_PAGE'     => $LIMIT,
																'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																'L_SINGLE'     => $this->ipsclass->compiled_templates['skin_global']->pagination_compile($this->ipsclass->compiled_templates['skin_global']->pagination_make_jump(),"","",$this->ipsclass->compiled_templates['skin_global']->pagination_current_page(1),"","",1,$LIMIT,$this->ipsclass->market_class->base_url."plugin={$this->ipsclass->input['plugin']}&amp;do=logs",0,'st'),
																'BASE_URL'     => $this->ipsclass->market_class->base_url."plugin={$this->ipsclass->input['plugin']}&amp;do=bought",
																'USE_ST'       => 'st'
														)	);
		
		$items = array();
		$this->ipsclass->DB->build_query(array(
												'select' => 'l.*',
												'from' => array('market_user_store_logs'=>'l'),
												'where' => "l.buyer_id=".$this->ipsclass->member['id'],
												'add_join' => array(
																		array(
																				'select' => 's.members_display_name as seller_name, s.mgroup as seller_group',
																				'from' => array('members'=>'s'),
																				'where' => "l.seller_id=s.id",
																				'type' => 'left',
																			),
																	),
												'order' => "time_bought DESC",
												'limit' => array($this->ipsclass->input['st'],$LIMIT),
										)	);
		$q = $this->ipsclass->DB->exec_query();
		while($item = $this->ipsclass->DB->fetch_row($q))
		{
			if(!is_array($this->ipsclass->cache['market_items'][$item['item']]))
			{
				$this->ipsclass->DB->do_delete('market_user_store_item',"i_id=".$item['i_id']);
				continue;
			}
			
			$item['price_bought'] = $item['price'];
			$item['resell_price'] = 0;
			$item['price'] = $this->ipsclass->numbers->format_currency($item['price']);
			$item['time_bought'] = $this->ipsclass->get_date($item['time_bought'],'SHORT');
			$item['seller_name'] = $this->ipsclass->market_class->format_name($item['seller_id'],$item['seller_name'],$item['seller_group']);
			$item['description'] = $this->ipsclass->parser->pre_display_parse($this->ipsclass->parser->pre_db_parse($this->ipsclass->market_class->items_loaded[$item['item']]->parse_single_description($item)));
			$items[] = $item;
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->ustore_bought_item_page($items,$page_links);
	}
	
	function run_sold_items()
	{
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		$LIMIT = 25;
		
		$this->ipsclass->subtitle = $this->ipsclass->lang['ustore_sold_logs'];
		$this->ipsclass->nav = array("<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}'>".$this->plugin['name']."</a>","<a href='{$this->ipsclass->market_class->base_url}plugin={$this->plugin['link']}&amp;do=sold'>".$this->ipsclass->lang['ustore_sold_logs']."</a>");
		
		$rows = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_transfer_logs','where'=>"l_link='".$this->ipsclass->input['plugin']."' AND (l_from=".$this->ipsclass->member['id']." OR l_to=".$this->ipsclass->member['id'].")"));
		$page_links = $this->ipsclass->build_pagelinks(	array(	'TOTAL_POSS'   => $rows['total'],
																'PER_PAGE'     => $LIMIT,
																'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																'L_SINGLE'     => $this->ipsclass->compiled_templates['skin_global']->pagination_compile($this->ipsclass->compiled_templates['skin_global']->pagination_make_jump(),"","",$this->ipsclass->compiled_templates['skin_global']->pagination_current_page(1),"","",1,$LIMIT,$this->ipsclass->market_class->base_url."plugin={$this->ipsclass->input['plugin']}&amp;do=logs",0,'st'),
																'BASE_URL'     => $this->ipsclass->market_class->base_url."plugin={$this->ipsclass->input['plugin']}&amp;do=bought",
																'USE_ST'       => 'st'
														)	);
		
		$items = array();
		$this->ipsclass->DB->build_query(array(
												'select' => 'l.*',
												'from' => array('market_user_store_logs'=>'l'),
												'where' => "l.seller_id=".$this->ipsclass->member['id'],
												'add_join' => array(
																		array(
																				'select' => 'b.members_display_name as buyer_name, b.mgroup as buyer_group',
																				'from' => array('members'=>'b'),
																				'where' => "l.buyer_id=b.id",
																				'type' => 'left',
																			),
																	),
												'order' => "time_bought DESC",
												'limit' => array($this->ipsclass->input['st'],$LIMIT),
										)	);
		$q = $this->ipsclass->DB->exec_query();
		while($item = $this->ipsclass->DB->fetch_row($q))
		{
			if(!is_array($this->ipsclass->cache['market_items'][$item['item']]))
			{
				$this->ipsclass->DB->do_delete('market_user_store_item',"i_id=".$item['i_id']);
				continue;
			}
			
			$item['price_bought'] = $item['price'];
			$item['resell_price'] = 0;
			$item['price'] = $this->ipsclass->numbers->format_currency($item['price']);
			$item['time_bought'] = $this->ipsclass->get_date($item['time_bought'],'SHORT');
			$item['buyer_name'] = $this->ipsclass->market_class->format_name($item['buyer_id'],$item['buyer_name'],$item['buyer_group']);
			$item['description'] = $this->ipsclass->parser->pre_display_parse($this->ipsclass->parser->pre_db_parse($this->ipsclass->market_class->items_loaded[$item['item']]->parse_single_description($item)));
			$items[] = $item;
		}
		
		$this->ipsclass->output .= $this->ipsclass->compiled_templates['skin_market_plugin']->ustore_sold_item_page($items,$page_links);
	}
	
	function order($a,$b)
	{
		if($this->order[$this->ipsclass->input['order']] != '')
		{
			if($this->ipsclass->input['order'] == 'expire')
			{
				$_a = $this->ipsclass->numbers->compare($a[$this->order[$this->ipsclass->input['order']]],0);
				$_b = $this->ipsclass->numbers->compare($b[$this->order[$this->ipsclass->input['order']]],0);
				$ab = $this->ipsclass->numbers->compare($a[$this->order[$this->ipsclass->input['order']]],$b[$this->order[$this->ipsclass->input['order']]]);
				if(($ab > 0 || $_a == 0) && $_b > 0)
				{
					return 1 * $this->order_by[$this->ipsclass->input['by']];
				}
				elseif(($ab < 0 || $_b == 0) && $_a > 0)
				{
					return -1 * $this->order_by[$this->ipsclass->input['by']];
				}
				else
				{
					return $this->second_order($a,$b);
				}
			}
			if($a[$this->order[$this->ipsclass->input['order']]] > $b[$this->order[$this->ipsclass->input['order']]])
			{
				return 1 * $this->order_by[$this->ipsclass->input['by']];
			}
			elseif($a[$this->order[$this->ipsclass->input['order']]] < $b[$this->order[$this->ipsclass->input['order']]])
			{
				return -1 * $this->order_by[$this->ipsclass->input['by']];
			}
			else
			{
				return 0;
			}
		}
		else
		{
			$translate = array('name'=>'item_name','icon'=>'icon');
			if($this->ipsclass->input['order'] == 'category')
			{
				$a_2 = $this->ipsclass->market_class->category_order[$this->ipsclass->cache['market_items'][$a['item']]['category']];
				$b_2 = $this->ipsclass->market_class->category_order[$this->ipsclass->cache['market_items'][$b['item']]['category']];
				if($a_2 < $b_2)
				{
					return 1 * $this->order_by[$this->ipsclass->input['by']];
				}
				elseif($a_2 > $b_2)
				{
					return -1 * $this->order_by[$this->ipsclass->input['by']];
				}
				else
				{
					return 0;
				}
			}
			else
			{
				$a_2 = $this->ipsclass->cache['market_items'][$a['item']][$translate[$this->ipsclass->input['order']]];
				$b_2 = $this->ipsclass->cache['market_items'][$b['item']][$translate[$this->ipsclass->input['order']]];
				return strcasecmp($a_2,$b_2) * $this->order_by[$this->ipsclass->input['by']];
			}
		}
	}
}
?>